package com.admin_system.service.impl;

import com.admin_system.service.FileService;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public Resource mergeFiles(MultipartFile examFile, MultipartFile answerFile) throws Exception {
        // 直接合并两个文件的二进制内容，而不是尝试作为PDF处理
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        
        // 复制第一个文件(试卷)到输出流
        try (InputStream examInputStream = examFile.getInputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = examInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        
        // 在两个文件之间添加分隔页（可选，这里简单添加一些换行）
        outputStream.write("\n\n--- 答案部分 ---\n\n".getBytes());
        
        // 复制第二个文件(答案)到输出流
        try (InputStream answerInputStream = answerFile.getInputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = answerInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        
        // 返回合并后的内容
        return new ByteArrayResource(outputStream.toByteArray());
    }

    private void validateFileType(MultipartFile file) {
        String contentType = file.getContentType();
        if (contentType == null || (!contentType.equals("application/pdf") 
                && !contentType.equals("application/msword")
                && !contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))) {
            throw new IllegalArgumentException("不支持的文件类型");
        }
    }
} 